import React, {useEffect, useState} from 'react';

import {AutoComplete, Button, Col, Divider, Form, Input, message, Row, Select, Space} from 'antd';
import {MinusCircleOutlined, PlusCircleOutlined} from '@ant-design/icons';
import {getDatabaseSearchItemText} from '../utils/convert';

import style from './ComplexSearch.module.scss';
import {getKeys, splitSentence} from '../network/requests';

const {useForm} = Form;

const {Option} = Select;
const {Search} = Input;

export default function ComplexSearch(props) {
  const [isComplex, setIsComplex] = useState(false);
  const onFinish = (values) => {
    props.onSearch(values);
  };

  const [keys, setKeys] = useState([]);
  const [form] = useForm();

  useEffect(() => {
    getKeys().then((keys) => {
      setKeys(keys.slice(0, 10));
    });
  }, []);

  // const options=useMemo(()=>{
  //   const o={};
  //   keys.forEach(({key, id})=>{
  //     o[key]=key;
  //   });
  //   return o;
  // }, [keys]);

  return <>
    <Row style={{display: isComplex ? 'none' : 'flex'}} align={'middle'}>
      <Col flex={'1 0 0'}>
        <AutoComplete style={{width: '100%'}} options={keys.map(({key}) => ({
          value: key,
        }))}>
          <Search
            loading={props.loading}
            enterButton="简单搜索"
            size="large"
            placeholder={'请输入关键词'}
            onSearch={(value) => {
              if (!value) {
                message.error('请输入关键词');
                return;
              }
              props.setLoading(true);
              splitSentence(value).then((result) => {
                form.setFieldsValue({
                  searchComplex: result.map((query) => ({
                    from: 'all',
                    query: [query],
                  })),
                });
                // setIsComplex(true);
                form.submit();
              });
            }}/>
        </AutoComplete>
      </Col>
      <Col>
        <Button onClick={() => {
          setIsComplex(true);
        }} type={'link'}>高级搜索</Button>
      </Col>
    </Row>
    <Form style={{display: !isComplex ? 'none' : 'block'}} form={form} initialValues={{
      searchComplex: [{
        from: 'all',
        query: [],
      }],
    }} className={style.complexForm} onFinish={onFinish} autoComplete="off">
      <Form.List name="searchComplex">
        {(fields, {add, remove}) => (
          <>
            {fields.map(({key, name, ...restField}) => (
              <div key={key}>
                {name !== 0 &&
                <Divider orientation={'left'} key={key + 'divider'} className={style.divider} plain>并且</Divider>}
                <Space key={key} style={{display: 'flex'}} align="baseline">
                  <Form.Item
                    {...restField}
                    name={[name, 'query']}
                    rules={[{required: true, message: '请输入关键词'}]}
                    label={'关键词：'}
                  >
                    <Select
                      mode={'tags'}
                      style={{width: '300px'}}
                      tokenSeparators={[' ', ',']}
                      placeholder="多个关键词用空格分隔，表示逻辑或"
                    >
                      {
                        keys.map((({key}) => <Option key={key}>{key}</Option>))
                      }
                    </Select>
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'from']}
                    rules={[{required: true, message: '请选择来源'}]}
                    label={'出现在：'}
                  >
                    <Select
                      style={{width: '120px'}}>
                      {Object.keys(getDatabaseSearchItemText).map((key) => {
                        return <Option key={key}>{getDatabaseSearchItemText[key]}</Option>;
                      })}
                    </Select>
                  </Form.Item>
                  {
                    fields.length !== 1 && <MinusCircleOutlined onClick={() => remove(name)}/>
                  }
                  {
                    name === fields.length - 1 && <PlusCircleOutlined onClick={() => add({
                      from: 'all',
                    })}/>
                  }
                </Space>
              </div>
            ))}
            <Form.Item>
              <Space>
                <Button
                  loading={props.loading} type="primary" htmlType="submit">
                  高级搜索
                </Button>
                <Button type={'link'} onClick={() => {
                  setIsComplex(false);
                }}>简单搜索</Button>
              </Space>
            </Form.Item>
          </>
        )}
      </Form.List>
    </Form>
  </>;
}
